# -*- coding: utf-8 -*-
"""
Created on 2022/11/3 下午8:17

@author: chenfei
"""

import sys
sys.path.append('..')
from django.shortcuts import render
from django.http import JsonResponse
from django.urls import reverse
from django.shortcuts import redirect
import json
import MyRpc.MyDb as mydb

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

'''
加密解密
'''
class MyCrypto(object):
    _key = 'wudafuisa suaige';
    _iv = 'afu is an suaige';

    def _add_to_16(self, text):
        if len(text.encode('utf-8')) % 16:
            add = 16 - (len(text.encode('utf-8')) % 16);
        else:
            add = 0;
        text = text + ('\0' * add);
        return text.encode('utf-8');

    def encrypt(self, msg):
        obj = AES.new(self._key, AES.MODE_CBC, self._iv);
        return bytes.decode(b2a_hex(obj.encrypt(self._add_to_16(msg))));

    def decrypt(self, msg):
        obj2 = AES.new(self._key, AES.MODE_CBC, self._iv);
        return bytes.decode(obj2.decrypt(a2b_hex(msg))).rstrip('\0');

    pass;


'''
  登录页面
'''
def login_page(request):
    rsp = render(request, 'app/login.html');
    rsp.delete_cookie('user');
    return rsp;

'''
首页
'''
def index(request):
    obj = {'current': 'guide', 'li_cur': 'guide'};
    return render(request, 'app/index.html', {'m': obj});

'''
入门指南
'''
def guide(request):
    obj = {'current': 'guide', 'li_cur': 'guide'};
    return render(request, 'app/guide.html', {'m': obj});

'''
介绍
'''
def introduce(request):
    obj = {'current': 'guide', 'li_cur': 'introduce'};
    return render(request, 'app/introduce.html', {'m': obj});

'''
安装
'''
def installation(request):
    obj = {'current': 'guide', 'li_cur': 'installation'};
    return render(request, 'app/installation.html', {'m': obj});

'''
链接数据库
'''
def linkdb(request):
    obj = {'current': 'guide', 'li_cur': 'linkdb'};
    return render(request, 'app/linkdb.html', {'m': obj});

'''
Dawn Sql 设计思想
'''
def design(request):
    obj = {'current': 'guide', 'li_cur': 'design'};
    return render(request, 'app/design.html', {'m': obj});

'''
对应用架构的支持
'''
def support(request):
    obj = {'current': 'guide', 'li_cur': 'support'};
    return render(request, 'app/support.html', {'m': obj});

'''
ddl
'''
def ddl(request):
    obj = {'current': 'guide', 'li_cur': 'ddl'};
    return render(request, 'app/ddl.html', {'m': obj});

'''
dml
'''
def dml(request):
    obj = {'current': 'guide', 'li_cur': 'dml'};
    return render(request, 'app/dml.html', {'m': obj});

'''
nosql
'''
def nosql(request):
    obj = {'current': 'guide', 'li_cur': 'nosql'};
    return render(request, 'app/nosql.html', {'m': obj});

'''
schedule
'''
def schedule(request):
    obj = {'current': 'guide', 'li_cur': 'schedule'};
    return render(request, 'app/schedule.html', {'m': obj});

'''
高性能程序的开发
'''
def hp(request):
    obj = {'current': 'guide', 'li_cur': 'hp'};
    return render(request, 'app/hp.html', {'m': obj});

'''
自定义扩展方法
'''
def customextension(request):
    obj = {'current': 'guide', 'li_cur': 'customextension'};
    return render(request, 'app/customextension.html', {'m': obj});

'''
jdbc
'''
def jdbc(request):
    obj = {'current': 'guide', 'li_cur': 'jdbc'};
    return render(request, 'app/jdbc.html', {'m': obj});

'''
ml
'''
def ml(request):
    obj = {'current': 'guide', 'li_cur': 'ml'};
    return render(request, 'app/ml.html', {'m': obj});

'''
集群异地强一致性实时多活
'''
def cluster(request):
    obj = {'current': 'guide', 'li_cur': 'cluster'};
    return render(request, 'app/cluster.html', {'m': obj});

'''
为什么要发明DawnSql语言
'''
def whydawnsql(request):
    obj = {'current': 'dawnsql', 'li_cur': 'whydawnsql'};
    return render(request, 'app/whydawnsql.html', {'m': obj});

'''
DawnSql语法
'''
def dawnsql(request):
    obj = {'current': 'dawnsql', 'li_cur': 'dawnsql'};
    return render(request, 'app/dawnsql.html', {'m': obj});

'''
操作数据库的函数
'''
def dawndb(request):
    obj = {'current': 'dawnsql', 'li_cur': 'dawndb'};
    return render(request, 'app/dawndb.html', {'m': obj});

'''
掌中宝
'''
def func(request):
    obj = {'current': 'func', 'li_cur': 'func'};
    return render(request, 'app/func.html', {'m': obj});

'''
登录
'''
def login(request):
    return render(request, 'app/login.html');

'''
登录用户组
'''
def login_db(request):
    if request.POST.get('user_token') is not None:
        user_token = request.POST.get('user_token');
        vs = mydb.login(user_token);
        if vs is not None and len(vs[0]) > 0:
            cry = MyCrypto();
            en = cry.encrypt(user_token);
            #resp = render(request, 'app/dawnclient_3.html');
            resp = redirect('/dawnclient/');
            resp.set_cookie('user_token', en);
            return resp;
    return redirect('/login/');

'''
ajax 登录用户组
'''
def ajax_login_db(request):
    if request.POST.get('user_token') is not None:
        user_token = request.POST.get('user_token');
        vs = mydb.login(user_token);
        if vs is not None and len(vs[0]) > 0:
            cry = MyCrypto();
            en = cry.encrypt(user_token);
            #resp = render(request, 'app/dawnclient_3.html');
            resp = JsonResponse({'vs': 1});
            resp.set_cookie('user_token', en);
            return resp;
    return JsonResponse({'vs': 0});

'''
注册
'''
def register(request):
    return render(request, 'app/register.html');

'''
注册用户组
'''
def register_db(request):
    if request.POST.get('group_name') is not None and request.POST.get('user_token') is not None:
        group_name = request.POST.get('group_name');
        user_token = request.POST.get('user_token');
        vs = mydb.register_db(group_name, user_token);
        if vs == 1:
            cry = MyCrypto();
            en = cry.encrypt(group_name + user_token);
            #resp = render(request, 'app/dawnclient_3.html');
            resp = redirect('/dawnclient/');
            resp.set_cookie('user_token', en);
            return resp;
    return redirect('/register/');

'''
判断是否注册
'''
def re_register(request):
    if request.GET.get('group_name') is not None and request.GET.get('user_token') is not None:
        group_name = request.GET.get('group_name');
        vs = mydb.re_register(group_name);
        if vs is not None and len(vs) == 1:
            return JsonResponse({'vs': 1});

    return JsonResponse({'vs': 0});

'''
工作台
'''
def dawnclient(request):
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        if user_token is not None:
            obj = {'user_token': user_token};
            return render(request, 'app/dawnclient_3.html', {'m': obj});
    return redirect('/login/');

'''
dawnclient_4 的例子
'''
def dawnclient_4(request):
    return render(request, 'app/dawnclient_4.html');

'''
dawnclient_5 的例子
'''
def dawnclient_5(request):
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        if user_token is not None:
            work_id = '';
            if request.GET.get('work_id') is not None:
                work_id = request.GET.get('work_id');
            obj = {'user_token': user_token, 'work_id': work_id};
            return render(request, 'app/dawnclient_5.html', {'m': obj});
    return redirect('/login/');

'''
dawnclient_6 的例子
'''
def dawnclient_6(request):
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        if user_token is not None:
            obj = {'user_token': user_token};
            return render(request, 'app/dawnclient_6.html', {'m': obj});
    return redirect('/login/');

'''
dawnclient_7 的例子
'''
def dawnclient_7(request):
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        if user_token is not None:
            work_id = '';
            if request.GET.get('work_id') is not None:
                work_id = request.GET.get('work_id');
            obj = {'user_token': user_token, 'work_id': work_id};
            return render(request, 'app/dawnclient_7.html', {'m': obj});
    return redirect('/login/');

'''
my_iframe 的例子
'''
def my_iframe(request):
    return render(request, 'app/my_iframe.html');

'''
localStorage 的例子
'''
def localStorage(request):
    return render(request, 'app/localStorage.html');

'''
工作台  
'''
def workbench(request):
    return render(request, 'app/workbench_1.html');

'''
展示数据
'''
def data(request):
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        obj = {'columns_name': None, 'columns': None};
        if request.GET.get('schema') is not None and request.GET.get('table_name') is not None:
            schema = request.GET.get('schema');
            table_name = request.GET.get('table_name');
            obj['schema'] = schema;
            obj['table_name'] = table_name;

            vs = mydb.read_column_meta(user_token, schema, table_name);
            if isinstance(vs, dict) and vs.__contains__('err') == False:
                columns_name = '';
                columns = '';
                index = 0;
                for k in vs:
                    if index == len(vs) - 1:
                        columns_name += "'{0}'".format(k);
                        columns += "{" + "text : '{0}', dataIndex : '{0}', tooltip: '{0}'".format(k) + "}";
                        index = index + 1;
                    else:
                        columns_name += "'{0}',".format(k);
                        #columns += "{ text : '{0}', dataIndex : '{0}', tooltip: '{0}'},".format(k)
                        columns += "{" + "text : '{0}', dataIndex : '{0}', sortable: false, tooltip: '{0}'".format(k) + "},";
                        index = index + 1;
                obj['columns_name'] = "[" + columns_name + "]";
                obj['columns'] = "[" + columns + "]";
                obj['vs'] = vs;
                return render(request, 'app/data.html', {'m': obj});
            elif isinstance(vs, dict) and vs.__contains__('err'):
                return render(request, 'app/err.html', {'m': vs});

    return render(request, 'app/data.html');

'''
data_show
'''
def data_show(request):
    rs = {'totalProperty': 0, 'root': []}
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        if request.GET.get('schema') is not None and request.GET.get('table_name') is not None:
            schema = request.GET.get('schema');
            table_name = request.GET.get('table_name');
            #start = int(request.GET.get('start'));
            page = int(request.GET.get('page'));
            limit = int(request.GET.get('limit'));
            totalProperty = mydb.get_table_count(user_token, schema, table_name);
            root = mydb.get_table_row(user_token, schema, table_name, limit * (page - 1), limit);
            rs = {'totalProperty': totalProperty, 'root': root}
    return JsonResponse(rs);

'''
tree store
'''
def tree(request):
    if request.GET.get('id') is not None:
        user_token = request.GET.get('user_token');
        p = request.GET.get('id');
        if p == "root":
            rs = {'root': mydb.get_schemas(user_token)};
        else:
            rs = {'root': mydb.get_tables(user_token, p)};

    #rs = {'root': root};
    return JsonResponse(rs);

'''
运行 sql
'''
def run_sql(request):
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        code = request.POST.get('code');
        if request.POST.get('select') is not None and int(request.POST.get('select')) == 1:
            vs = '';
            try:
                vs = mydb.run_select_meta(user_token, code);
                if isinstance(vs, dict) and vs.__contains__('err') == False:
                    columns_name = [];
                    columns = [];
                    for k in vs:
                        columns_name.append(k);
                        columns.append({'text': k, 'dataIndex': k, 'tooltip': k});
                    return JsonResponse({'columns_name': columns_name, 'columns': columns});
                elif isinstance(vs, dict) and vs.__contains__('err'):
                    if vs.__contains__('err'):
                        return JsonResponse(vs);
            except Exception as ex:
                return vs;
        else:
            vs = '';
            try:
                vs = mydb.run_dawn_sql(user_token, code);
                if isinstance(vs, dict) and vs.__contains__('msg'):
                    return JsonResponse(vs);
                elif isinstance(vs, dict) and vs.__contains__('err'):
                    if vs.__contains__('err'):
                        return JsonResponse(vs);
            except Exception as ex:
                return vs;

'''
load code to db
'''
def load_code(request):
    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        code = request.POST.get('code');
        vs = mydb.load_code(user_token, code);
        if isinstance(vs, dict) and vs.__contains__('msg'):
            return JsonResponse(vs);
        elif isinstance(vs, dict) and vs.__contains__('err'):
            if vs.__contains__('err'):
                return JsonResponse(vs);

'''
运行 sql store
'''
def run_select_sql(request):
    root = [];

    cry = MyCrypto();
    c_user_token = request.COOKIES.get('user_token');
    if c_user_token is not None:
        user_token = cry.decrypt(c_user_token);
        code = request.POST.get('code');
        page = int(request.POST.get('page'));
        limit = int(request.POST.get('limit'));
        vs = mydb.run_select(user_token, code, limit * (page - 1), limit);
        return JsonResponse(vs);

    rs = {'root': root};
    return JsonResponse(rs);

'''
开发建议
'''
def suggest(request):
    obj = {'current': 'default'};
    return render(request, 'app/suggest.html', {'m': obj});

'''
贡献者
'''
def team(request):
    obj = {'current': 'team', 'li_cur': 'team'};
    return render(request, 'app/team.html', {'m': obj});

'''
团队
'''
def my_team(request):
    return render(request, 'app/my_team.html');

'''
template
'''
def tmp(request):
    return render(request, 'app/tmp.html');

'''
err  
'''
def err(request):
    vs = {'err': '吴大富'};
    return render(request, 'app/err.html', {'m': vs});

'''
正则式
'''
def re(request):
    return render(request, 'app/re.html');

'''
MyWeb
'''
def MyWeb(request):
    return render(request, 'app/MyWeb.html');


